package com.mzmarket.market.module.service;

import com.mzmarket.market.module.entity.Category;
import com.mzmarket.market.module.mapper.CategoryMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class CategoryService {

    @Resource
    private CategoryMapper categoryMapper;

    public Category getById(Long id) {
        if (id == null) {
            throw new RuntimeException("CategoryId cannot be null or empty");
        }
        return categoryMapper.getById(id);
    }

    public Category extractById(Long id) {
        if (id == null) {
            throw new RuntimeException("Id cannot be null or empty");
        }
        return categoryMapper.extractById(id);
    }

    public int insert(Category category) {
        return categoryMapper.insert(category);
    }

    public int update(Category category) {
        return categoryMapper.update(category);
    }

    public int delete(Long id) {
        if (id == null) {
            throw new RuntimeException("Id cannot be null or empty");
        } else {
            if (getById(id) == null) {
                throw new RuntimeException("Category not found");
            }
        }
        int timeStamp = (int) (System.currentTimeMillis() / 1000);
        return categoryMapper.delete(id, timeStamp);
    }

    public Long edit(
            Long id,
            String name,
            String image
    ) throws RuntimeException {
        int timeStamp = (int) (System.currentTimeMillis() / 1000);
        Category category = new Category();

        category.setName(name);
        category.setImage(image);
        category.setIsDeleted(0);

        if (id == null) {//插入业务需要判断每一项不为空
            if (name == null || name.trim().isEmpty()) {
                throw new RuntimeException("Name cannot be null or empty");
            }
            if (image == null || image.trim().isEmpty()) {
                throw new RuntimeException("Image cannot be null or empty");
            }
            category.setCreateTime(timeStamp);
            insert(category);
        } else {
            category.setId(id);
            if (getById(id) == null) {
                throw new RuntimeException("Product not found");
            } else {
                update(category);
            }
        }
        return category.getId();
    }

    public List<Category> getCategoryList(){
        return categoryMapper.getAll();
    }
}